import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import styles from '../../assets/style/UserManage.module.css';
import {
	Button,
	Modal,
	Input,
	Table,
	Tag,
	Form,
	message,
	Popconfirm,
} from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import {
	getUsers,
	updatePassword,
	deluserbyusername,
	addTrafficUser,
	changeOnline,
} from '../../request/http';

export default function UserManage(props) {
	const [isManageshow, setManageshow] = useState(false);
	const [size, setSize] = useState(5); // 显示的每页条数
	const [page, setPage] = useState(1); // 显示第几页
	const [total, setTotal] = useState(200); //总共多少条数据
	const [pageData, setPageData] = useState([]); // 显示在表格中每页的数据
	const [isUpdatashow, setUpdatashow] = useState(false); // 修改密码的弹窗显隐
	const [oldUsername, setOldusername] = useState('123'); //用户名
	const [isaddshow, setAddshow] = useState(false); // 新增用户的显隐
	const [form] = Form.useForm(); //定义form的引用
	const [inputSearch, setinputSearch] = useState(''); //搜索控的值
	useEffect(() => {
		if (props.itemkey == 2) {
			setManageshow(true);
			getUsers(`/user?page=${page}&size=${size}`).then((res) => {
				if (res.code == 0) {
					const { data, total } = res.result;
					setTotal(total);
					init_pageData(data);
				}
			});
		}
	}, [props.itemkey]);
	const okManage = () => {
		setManageshow(false);
		props.resetItemkey();
	};
	/* 初始化用户页 */
	const init_pageData = (data) => {
		const users = [];
		data.map((item) => {
			const element = {};
			element.key = item.user_name; //因为用户名是唯一的，所以可以作为key
			element.username = item.user_name;
			element.usertype = item.user_type;
			element.user_onlinestatus = item.user_onlinestatus;
			users.push(element);
		});
		setPageData(users);
	};
	/* 定义分页器改变触发的函数 */
	const PageandSizeChange = (page, size) => {
		getUsers(`/user?page=${page}&size=${size}`).then((res) => {
			if (res.code == 0) {
				const { data, total } = res.result;
				setTotal(total);
				init_pageData(data);
				setPage(page);
				setSize(size);
			}
		});
	};
	/* 点击修改按钮触发 */
	const changePwd = (data) => {
		setUpdatashow(true);
		setOldusername(data.username);
	};
	const closeUpdate = () => {
		setUpdatashow(false);
	};
	/* 修改用户信息的表单相关方法 */
	const onFinish = (value) => {
		const info = {
			oldusername: oldUsername,
			newusername: value.username,
			newpwd: value.password,
		};
		updatePassword('/user', info).then((res) => {
			if (res.code == 0) {
				message.success('修改用户信息成功');
				setUpdatashow(false);
				/* 修改密码完成后，更新table */
				PageandSizeChange(page, size);
				form.resetFields();
			}
		});
	};
	const onFinishFailed = () => {};
	/* 删除用户相关 */
	const okdeluser = (data) => {
		const item = { username: data.username };
		deluserbyusername('/user', item).then((res) => {
			if (res.code == 0) {
				PageandSizeChange(page, size);
			}
		});
	};
	/* 新增用户相关 */
	const addUser = () => {
		setAddshow(true);
	};
	const closeAdd = () => {
		setAddshow(false);
	};
	const okadduser = (value) => {
		const item = {
			user_name: value.username,
			user_password: value.password,
			user_type: 'traffic',
		};
		/* 执行新增用户前，应该查询所有用户名，不能添加相同用户名的用户 */
		getUsers(`/user?page=1&size=1000`).then((res) => {
			if (res.code == 0) {
				const { data } = res.result;
				const flag = data.find((item) => {
					return item.user_name == value.username;
				});
				/* 如果没找到 则flag=undefined ，则执行添加*/
				if (!flag) {
					addTrafficUser('/user', item).then((res) => {
						if (res.code == 0) {
							form.resetFields();
							setAddshow(false);
							message.success('添加交管用户成功');
							PageandSizeChange(page, size);
						}
					});
				} else {
					message.error('该用户已存在，请重新输入');
					form.resetFields();
				}
			}
		});
	};
	const Failedadduser = () => {};
	/* 搜索相关的方法 */
	const okSearch = (e) => {
		let keyword = e.target.value;
		setinputSearch(keyword);
		getUsers(
			`/user?page=${page}&size=${size}&keyword=${keyword == '' ? '.' : keyword}`
		).then((res) => {
			if (res.code == 0) {
				if (keyword == '') {
					const { data, total } = res.result;
					setTotal(total);
					init_pageData(data);
				} else {
					const { keywordData, total } = res.result;
					setTotal(keywordData.length);
					init_pageData(keywordData);
				}
				setPage(page);
				setSize(size);
			}
		});
	};
	/* 下线相关 */
	const okOffline = (value) => {
		console.log(value);
		changeOnline(`username=${value.username}&online=0`);
		PageandSizeChange(page, size);
	};
	const columns = [
		{
			title: '用户名',
			width: '20%',
			align: 'center',
			dataIndex: 'username',
			key: 'username',
		},
		{
			title: '用户类型',
			width: '20%',
			align: 'center',
			dataIndex: 'usertype',
			key: 'usertype',
			render: (value, rowdata, index) => {
				if (value == 'user') {
					return <span>普通用户</span>;
				} else if (value == 'traffic') {
					return <span>交管用户</span>;
				} else {
					return <span>管理员</span>;
				}
			},
		},
		{
			title: '登录状态',
			width: '12%',
			align: 'center',
			dataIndex: 'user_onlinestatus',
			key: 'user_onlinestatus',
			render: (value, row, index) => {
				return (
					<div>
						{value ? (
							<Tag color={'green'}>上线</Tag>
						) : (
							<Tag color={'red'}>下线</Tag>
						)}
					</div>
				);
			},
		},
		{
			title: '管理操作',
			width: '38%',
			align: 'center',
			dataIndex: 'user_onlinestatus',
			key: 'actions',
			render: (value, row, index) => {
				if (row.usertype == 'admin') {
					return <Tag color={'red'}>管理员无法删除修改！</Tag>;
				} else {
					return (
						<div>
							<Button
								style={{ marginLeft: '10px' }}
								type="primary"
								onClick={() => {
									changePwd(row);
								}}
							>
								修改
							</Button>
							<Popconfirm
								title="确定要删除该用户吗？删除后无法撤销！"
								onConfirm={() => {
									okdeluser(row);
								}}
								icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
							>
								<Button style={{ marginLeft: '20px' }} type="primary" danger>
									删除
								</Button>
							</Popconfirm>
							{value ? (
								<Popconfirm
									title="确定要让该用户下线吗？"
									onConfirm={() => {
										okOffline(row);
									}}
									icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
								>
									<Button
										style={{
											marginLeft: '20px',
											color: 'black',
											backgroundColor: 'rgb(212, 247, 14)',
										}}
										type="primary"
									>
										下线
									</Button>
								</Popconfirm>
							) : (
								''
							)}
						</div>
					);
				}
			},
		},
	];

	return (
		<div className={styles.container}>
			<Modal
				title="用户管理"
				visible={isManageshow}
				maskClosable={false}
				maskStyle={{ backgroundColor: 'transparent' }}
				onCancel={okManage}
				width="850px"
				footer={[
					<Button key="close" type="primary" onClick={okManage}>
						关闭窗口
					</Button>,
				]}
			>
				<div className={styles.content}>
					<div className={styles.header}>
						<Input
							placeholder="请输入关键字,用户类型用user或traffic查询"
							value={inputSearch}
							onChange={okSearch}
						></Input>
						<Button onClick={addUser} type="primary">
							新增用户
						</Button>
					</div>
					<Table
						bordered
						scroll={{ y: 300 }}
						columns={columns}
						dataSource={pageData}
						pagination={{
							showSizeChanger: true,
							pageSizeOptions: [2, 5, 10, 20],
							pageSize: size, //默认显示每页多少条
							current: page, //当前显示的页
							total: total, //一共多少条
							showQuickJumper: true, //是否显示跳转到第几页
							onChange: PageandSizeChange, // page或者size改变的回调
							showTotal: (total) => `共${total}条`, //自定义成中文共多少条
						}}
					></Table>
				</div>
			</Modal>
			<Modal
				title="修改用户信息"
				visible={isUpdatashow}
				maskClosable={false}
				maskStyle={{ backgroundColor: 'transparent' }}
				onCancel={closeUpdate}
				width="600px"
				footer={[
					<Button key="close" type="primary" onClick={closeUpdate}>
						关闭窗口
					</Button>,
				]}
			>
				<Form
					form={form}
					name="updateUserForm"
					labelCol={{
						span: 8,
					}}
					wrapperCol={{
						span: 16,
					}}
					onFinish={onFinish}
					onFinishFailed={onFinishFailed}
					autoComplete="off"
				>
					<Form.Item
						label="用户名"
						name="username"
						rules={[
							{
								required: true,
								message: '请输入用户名！',
							},
						]}
					>
						<Input placeholder={oldUsername} />
					</Form.Item>
					<Form.Item
						label="密码"
						name="password"
						rules={[
							{
								required: true,
								message: '请输入密码!',
							},
						]}
					>
						<Input.Password />
					</Form.Item>
					<Form.Item
						wrapperCol={{
							offset: 8,
							span: 16,
						}}
					>
						<Button type="primary" htmlType="submit">
							确认修改
						</Button>
					</Form.Item>
				</Form>
			</Modal>
			{/* 新增用户 */}
			<Modal
				title="新增交通部门的用户"
				visible={isaddshow}
				maskClosable={false}
				maskStyle={{ backgroundColor: 'transparent' }}
				onCancel={closeAdd}
				width="600px"
				footer={[
					<Button key="close" type="primary" onClick={closeAdd}>
						关闭窗口
					</Button>,
				]}
			>
				<Form
					form={form}
					name="addTrafficUserForm"
					labelCol={{
						span: 8,
					}}
					wrapperCol={{
						span: 16,
					}}
					onFinish={okadduser}
					onFinishFailed={Failedadduser}
					autoComplete="off"
				>
					<Form.Item
						label="用户名"
						name="username"
						rules={[
							{
								required: true,
								message: '请输入用户名！',
							},
						]}
					>
						<Input />
					</Form.Item>
					<Form.Item
						label="密码"
						name="password"
						rules={[
							{
								required: true,
								message: '请输入密码!',
							},
						]}
					>
						<Input.Password />
					</Form.Item>
					<Form.Item
						wrapperCol={{
							offset: 8,
							span: 16,
						}}
					>
						<Button type="primary" htmlType="submit">
							确认添加
						</Button>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
}
